<template>
    <div class="page-container">
        <!-- 工具栏 -->
        <TableHead
            :config="tableHeaderConfig"
            :searchdata.sync="filters"
            v-show="showSearch"
            @parentPageList="findPageList"
        >
            <template slot="company">
                <el-select v-model="filters.companyId" placeholder="请选择" size="mini" clearable>
                    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
                </el-select>
            </template>
        </TableHead>
        <el-card class="card-box">
            <table-tool-bar :showSearch.sync="showSearch" @queryTable="findPageList" :columns="columns">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </table-tool-bar>
            <!--表格树内容栏-->
            <Table
                :columns="columns"
                :data="tableTreeList"
                :rowKey="'treeId'"
                :loading="loading"
                :isPagination="false"
                :default-expand-all="true"
            >
                <template slot="isValid" slot-scope="{ scope }" v-if="scope.row.code">
                    <el-switch
                        v-model="scope.row.isValid"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleEnable(scope.row)"
                    ></el-switch>
                </template>
                <template slot="oper" slot-scope="{ scope }" v-if="scope.row.code">
                    <el-button
                        icon="el-icon-edit"
                        type="text"
                        size="mini"
                        v-if="scope.row.isValid === 1"
                        @click="handleEdit(scope.row)"
                    >
                        编辑
                    </el-button>
                    <el-button icon="el-icon-delete" type="text" size="mini" @click="handleDelete(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </Table>
        </el-card>

        <!--编辑与新增-->
        <EditItem
            v-model="dialogVisible"
            :data-form="dataForm"
            :dialog-config="dialogConfig"
            :data-form-rules="dataFormRules"
            :dialog-tag="dialogTag"
            width="700px"
            ref="deptForm"
            @submitForm="submitForm"
        >
            <template slot="company">
                <el-select
                    v-model="dataForm.companyId"
                    placeholder="请选择公司"
                    size="small"
                    class="width100"
                    :disabled="dialogTag === 'edit'"
                    @change="getDeptByCompany"
                >
                    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
                </el-select>
            </template>
            <template slot="parentName">
                <el-select
                    v-model="dataForm.parentId"
                    placeholder="请选择上级部门"
                    size="small"
                    clearable
                    class="width100"
                >
                    <el-option v-for="item in options" :key="item.id" :label="item.deptName" :value="item.id" />
                </el-select>
                <!-- 部门只有两级 所以用select -->
            </template>
        </EditItem>
    </div>
</template>

<script>
import TableHead from '@/components/TableHeadSearch'
import EditItem from '@/components/EditItem'
import TreeSelect from '@/components/TreeSelect'
import TableToolBar from '@/components/TableToolBar'
import {
    getDeptTableList,
    addDept,
    editDept,
    deleteDept,
    getCompanyList,
    getAllOneDept,
    deptEnable
} from '@/api/system/user.js'
import { mapState } from 'vuex'
import { confirm } from '@/utils/utils'
export default {
    name: 'dept',
    components: {
        EditItem,
        TableHead,
        TreeSelect,
        TableToolBar
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            filters: {
                isValid: null,
                companyId: null
            },
            companyList: [],
            tableTreeList: [],
            tableHeaderConfig: [
                {
                    title: '公司',
                    slot: 'company'
                },
                {
                    title: '是否启用',
                    code: 'isValid'
                }
            ],
            dataFormDefault: {
                id: '',
                companyId: '',
                deptCode: '',
                deptHierarchy: 1,
                deptName: '',
                description: '',
                parentId: ''
            },
            dataForm: {},
            dialogVisible: false,
            dataFormRules: {
                deptName: [
                    { required: true, message: '部门名称不能为空', trigger: 'blur' },
                    {
                        max: 10,
                        message: '长度在10个字符以内',
                        trigger: 'blur'
                    }
                ],
                deptCode: [
                    { required: true, message: '部门编号不能为空', trigger: 'blur' },
                    {
                        max: 20,
                        message: '长度在20个字符以内',
                        trigger: 'blur'
                    },
                    {
                        pattern: /^[5A-Za-z0-9-\_]+$/,
                        message: '部门编号只能输入字母、数字、下划线',
                        trigger: 'blur'
                    }
                ],
                companyId: [{ required: true, message: '公司不能为空', trigger: 'change' }]
            },
            columns: [
                { prop: 'name', label: '组织架构', visible: true, key: 'name', minWidth: '150' },
                { prop: 'code', label: '部门编码', visible: true, key: 'code' },
                { slot: 'isValid', label: '状态', align: 'center', width: '80', visible: true, key: 'isValid' },
                { prop: 'description', label: '描述', visible: true, key: 'description' },
                { label: '创建人/创建时间', type: 'createUser', visible: true, key: 'createUser' },
                { label: '更新人/更新时间', type: 'updateUser', visible: true, key: 'updateUser' },
                {
                    slot: 'oper',
                    label: '操作',
                    align: 'center',
                    visible: true,
                    key: 'oper'
                }
            ],
            // dialog 要渲染的数据json
            dialogConfig: [
                { title: '所属公司', code: 'companyId', slot: 'company' },
                { title: '上级部门', code: 'parentId', slot: 'parentName' },
                { title: '部门名称', code: 'deptName', type: 'input', maxlength: 10 },
                {
                    title: '部门编号',
                    code: 'deptCode',
                    type: 'input',
                    disabled: 'edit',
                    maxlength: 20
                },
                { title: '描述', code: 'description', type: 'textarea', maxlength: 20 }
            ],
            dialogTag: '', // 编辑与新增的标识
            popupTreeData: [],
            popupTreeProps: {
                label: 'name',
                children: 'children'
            },
            options: []
        }
    },
    computed: {
        ...mapState({
            themeColor: state => state.app.themeColor
        })
    },
    mounted() {
        this.findPageList()
        this.getCompanyList()
    },
    activated() {
        this.findPageList()
        this.getCompanyList()
    },
    methods: {
        getCompanyList() {
            getCompanyList().then(res => {
                this.companyList = res.data
            })
        },
        // 获取数据
        findPageList() {
            this.loading = true
            getDeptTableList(this.filters)
                .then(res => {
                    this.tableTreeList = res.data || []
                })
                .finally(() => {
                    this.loading = false
                })
        },
        getDeptByCompany(val) {
            getAllOneDept({ companyId: val }).then(res => {
                // 上级部门不能选择自己 把当前部门排除
                this.options = res.data.filter(item => {
                    return item.id !== this.dataForm.id
                })
            })
            this.dataForm.parentId = ''
        },
        // 显示新增界面
        handleAdd() {
            this.dialogVisible = true
            this.dataForm = Object.assign({}, this.dataFormDefault)
            this.options = []
            this.dialogTag = 'add'
        },
        // 显示编辑界面
        handleEdit(row) {
            this.dialogTag = 'edit'
            const { code, name } = row
            this.dialogVisible = true
            this.dataForm = {
                id: row.id,
                companyId: row.companyId,
                deptCode: code,
                deptHierarchy: row.deptHierarchy,
                deptName: name,
                description: row.description,
                parentId: row.parentId
            }
            getAllOneDept({ companyId: this.dataForm.companyId }).then(res => {
                // 上级部门不能选择自己 把当前部门排除
                this.options = res.data.filter(item => {
                    return item.id !== this.dataForm.id
                })
            })
        },
        // 删除
        handleDelete(id) {
            confirm('确定要删除吗').then(() => {
                deleteDept({ deptId: id }).then(res => {
                    this.findPageList()
                    this.$message.success(res.msg)
                })
            })
        },
        //启用禁用
        handleEnable(row) {
            const tip = row.isValid === 1 ? '确认启用选中记录吗？' : '确认禁用选中记录吗？'
            confirm(tip)
                .then(() => {
                    deptEnable({ deptId: row.id, isValid: row.isValid })
                        .then(res => {
                            this.$message.success(res.msg)
                            this.findPageList()
                        })
                        .catch(() => {
                            row.isValid = row.isValid === 0 ? 1 : 0
                        })
                })
                .catch(() => {
                    row.isValid = row.isValid === 0 ? 1 : 0
                })
        },
        // 表单提交
        submitForm(data) {
            let fetchApi = this.dialogTag === 'add' ? addDept : editDept
            data.deptHierarchy = data.parentId ? 2 : 1
            fetchApi(data).then(res => {
                this.$message.success(res.msg)
                this.findPageList()
                this.dataForm = Object.assign({}, this.dataFormDefault)
                this.dialogVisible = false
            })
        }
    }
}
</script>

<style scoped></style>
